var normal = document.getElementById('mode-normal');
var pressure = document.getElementById('mode-pressure');
var _testTenantId = null;
var _testUserId = null;
var _produceId = null;
var _deviceTypeId = null;
var _produceName = null;

function getModeParameter(testUserId, testTenantId, produceId, deviceTypeId, produceName) {
    _testTenantId = testTenantId;
    _testUserId = testUserId;
    _produceId = produceId;
    _deviceTypeId = deviceTypeId;
    _produceName = produceName;
    getDeviceList(deviceTypeId);
}

// getModeParameter(1, 160, 5249, 5559, '测试');
$(function () {
    $('.mode-checkbox').on('click', function () {//设置模式checkbox 互斥
        mode_set_checkbox(this);
    });


    $('.weui-navbar__item').on('click', function () {
        var url = $(this).attr('to-url');
        $(this).addClass('weui-bar__item_on').siblings('.weui-bar__item_on').removeClass('weui-bar__item_on');
        $(jQuery(this).attr("href")).show().siblings('.weui-tab__content').hide();
        if (url === 'getDeviceList') {
            // getDeviceList(1);
        } else if (url === 'testerMode') {
            TestPatternQuery(_testUserId, _testTenantId, _produceId);
        }
    });

    // Example functionality to demonstrate a value feedback
    // and change the output's value.
    function valueOutput(element, flag) {
        var value = element.value;
        var output = element.parentNode.getElementsByTagName('output')[0];
        var setValue = element.parentNode.getElementsByClassName('value')[0];
        var left = $(element).next('.rangeslider').find(".rangeslider__handle").css('left');
        $(output).css("left", left);
        if (flag == 1) {
            output.innerHTML = (value / 60) + "小时";
            setValue.value = (value);
        } else if (flag == 2) {
            output.innerHTML = value + "分钟";
            setValue.value = value;
        } else if (flag == 3) {
            output.innerHTML = value + "%";
            setValue.value = value;
        }

    }

    // Initial value output
    var selector = '[data-rangeslider]';
    var $inputRange = $(selector);
    /*for (var i = $inputRange.length - 1; i >= 0; i--) {
        valueOutput($inputRange[i]);
    }*/
    // Update value output
    $('#test-period-slider').on('input', function (e) {
        valueOutput(e.target, 1);
    });
    $('#cmd-interval-slider').on('input', function (e) {
        valueOutput(e.target, 2);
    });
    $('#success-radio-div').on('input', function (e) {
        valueOutput(e.target, 3);
    });

    // Initialize the elements
    $inputRange.rangeslider({
        polyfill: false
    });
});

function mode_set_checkbox(bean) {// //设置模式checkbox 互斥
    if (bean == normal) {
        if (normal.checked) assembleRadio(true, normal.checked, false);
        else assembleRadio(false, normal.checked, true);
    } else {
        if (pressure.checked) assembleRadio(false, false, pressure.checked);
        else assembleRadio(true, true, pressure.checked);
    }
    $('input[type="range"]').rangeslider('update', true);
}

function assembleRadio(disabledFlag, normalFlag, pressureFlag) {
    $('#success-radio-slider').attr("disabled", disabledFlag);
    $('#cmd-interval-slider').attr("disabled", disabledFlag);
    $('#test-period-slider').attr("disabled", disabledFlag);
    normal.checked = normalFlag;
    pressure.checked = pressureFlag;
    $('input[type="range"]').rangeslider('update', true);
}

function TestPatternQuery(testerId, tenantId, productId) {//测试模式查询
    $.ajax({
        type: "get",
        url: common.TestPatternQueryUrl,
        data: {"testUserId": testerId, "testTenantId": tenantId, "produceId": productId},
        dataType: 'json',
        success: function (result) {
            //这里是解析的json数据   直接返回data
            var resultData = result;
            var data = resultData.date;
            if (resultData.code == 0) {
                if (data.testType == 1) {
                    assembleRadio(false, false, true);
                    $('#test-period-slider').val(data.testPeriod).change();
                    $('#cmd-interval-slider').val(data.cmdInterval).change();
                    $('#success-radio-slider').val(data.successRadio).change();
                    $('#cmdInterval').val(data.cmdInterval);
                    $('#testPeriod').val(data.testPeriod);
                    $('#successRadio').val(data.successRadio);
                } else {
                    assembleRadio(true, true, false);
                    pressure.checked = false;
                    normal.checked = true;
                }
                window.wa.TestPatternQuery(parseInt(data.testType));
            } else {
                common.showMsgTips(resultData.msg);
                window.wa.TestPatternQuery(parseInt(3));
            }
            //数据格式
            //[{"code":0,"data":[{"attributeName":"温度","attributeValue":"0"},{"attributeName":"温度","attributeValue":"0"}],"msg":""}]
        }, error: function () {
            console.log("2222");
        }
    });
}

function submitTesterMode() {//测试模式提交
    var testerMode = {};
    testerMode['testTenantId'] = _testTenantId;
    testerMode['testUserId'] = _testUserId;
    testerMode['produceId'] = _produceId;
    testerMode['produceName']= _produceName;
    testerMode['deviceTypeId'] = _deviceTypeId;
    var testPeriod = $('#testPeriod').val();
    if (testPeriod == null) {
        testPeriod = 0;
    }
    var cmdInterval = $('#cmdInterval').val();
    if (cmdInterval == null) {
        cmdInterval = 0;
    }
    var successRadio = $('#successRadio').val();
    if (successRadio == null) {
        successRadio = 0;
    }
    testerMode['testPeriod'] = testPeriod;
    testerMode['cmdInterval'] = cmdInterval;
    testerMode['successRadio'] = successRadio;
    if (normal.checked) {//正常选择
        $('#testType').val(0);
    } else {//正常未选择
        $('#testType').val(1);
    }
    testerMode['testType'] = $('#testType').val();
    $.ajax({
        type: "post",
        url: common.TestPatternStoreUrl,
        data: testerMode,
        success: function (result) {
            //这里是解析的json数据   直接返回data
            var resultData = result;
            var data = resultData.data;
            if (resultData.code == 0) {
                common.showMsgTips("操作成功");
                window.wa.submitTesterMode(parseInt($('#testType').val()));// 正常是0 压力是1
            } else {
                common.showMsgTips(resultData.msg);
            }
            //数据格式
            //[{"code":0,"data":[{"attributeName":"温度","attributeValue":"0"},{"attributeName":"温度","attributeValue":"0"}],"msg":""}]
        }
    });
}

function getDeviceList(deviceTypeId) {//设备模型属性查询
    $.ajax({
        type: "get",
        url: common.getDeviceTypeContentUrl,
        data: {"deviceTypeID": deviceTypeId},
        success: function (result) {
            //这里是解析的json数据   直接返回data
            console.log(result);
            assembleDeviceRule(result);
            checkDeviceRule(_testTenantId, deviceTypeId);
            //数据格式
            //[{"code":0,"data":[{"attributeName":"温度","attributeValue":"0"},{"attributeName":"温度","attributeValue":"0"}],"msg":""}]
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //              $("#p_test").innerHTML = "there is something wrong!";
            console.log(XMLHttpRequest.status);
            console.log(XMLHttpRequest.readyState);
            console.log(textStatus);
        }
    });
}

function checkDeviceRule(testTenantId, deviceTypeId) {//校验规则查询
    $.ajax({
        type: "post",
        url: common.CheckRuleQueryUrl,
        data: {"testTenantId": testTenantId, "deviceTypeId": deviceTypeId},
        dataType: 'json',
        success: function (result) {
            console.log(result);
            //这里是解析的json数据   直接返回data
            var resultData = result;
            var list = resultData.listData;
            if (resultData.code == 0) {
                for (var i = 0; i < list.length; i++) {
                    var _o = list[i];
                    $('#setValue' + _o.detailNameCN).val(_o.setValue);
                    if (_o.isNull == 0) $('#radio2' + _o.detailNameCN).attr("checked", true);
                    else $('#radio1' + _o.detailNameCN).attr("checked", true);
                    $('#max' + _o.detailNameCN).val(_o.valueMax);
                    $('#min' + _o.detailNameCN).val(_o.valueMin);
                }
            } else {
                common.showMsgTips(resultData.msg);
            }
            //数据格式
            //[{"code":0,"data":[{"attributeName":"温度","attributeValue":"0"},{"attributeName":"温度","attributeValue":"0"}],"msg":""}]
        }
    });
}

function assembleDeviceRule(resultData) {
    var list = resultData.data.status;
    if (resultData.code == 0) {
        var str = '';//device
        for (var i = 0; i < list.length; i++) {
            var _o = list[i];
            str += '<table style="width: 100%; margin-top: 10px;background: #ffffff; "><tr><td style="width: 30%;">';
            str += '<input type="hidden" name="listData[' + i + '].attrcnName" value="' + list[i].detailNameCN + '">';
            str += '<input type="hidden" name="listData[' + i + '].binkey" value="' + list[i].binkey + '">';
            str += '<input type="hidden" name="listData[' + i + '].attrenName" value="' + list[i].detailNameEN + '">';
            str += '<div class="placeholder test-p-name">' + _o.detailNameCN + '</div></td><td style="width: 45%;"><div class="placeholder-radio-div">';
            str += '<input type="radio" id="radio1' + i + '" value="1" name="listData[' + i + '].isNull" ';
            // if (_o.readWriteType == 0) str += ' disabled ';
            str += 'checked/>';
            str += '<label for="radio1' + i + '" style="position: relative; padding: 0px 5px;"><div class="radioSpan ';
            // if (_o.readWriteType == 0) str += ' inputDisabled ';
            // else
                str += ' inputSuccess';
            str += '"></div> 可为空 </label>';
            str += '<input type="radio" id="radio2' + i + '" value="0" name="listData[' + i + '].isNull" ';
            // if (_o.readWriteType == 0) str += ' disabled ';
            str += '/>';
            str += '<label for="radio2' + i + '" style="position: relative; padding: 0px 5px;"><div class="radioSpan';
            // if (_o.readWriteType == 0) str += ' inputDisabled ';
            // else
                str += ' inputSuccess';
            str += '"></div> 不可为空 </label>';
            str += '</div></td><td style="width: 25%;">';
            // if (_o.dataType == 2) {
            //     str += '<div class="placeholder placeholder-min-max-div">';
            //     str += '<input type="text" placeholder="最小值" name="listData[' + i + '].valueMin"  id="min' + list[i].detailNameCN + '"';
            //     if (_o.readWriteType == 0) str += ' disabled ';
            //     str += '/>';
            //     str += '<input type="text" placeholder="最大值" name="listData[' + i + '].valueMax"  id="max' + list[i].detailNameCN + '"';
            //     if (_o.readWriteType == 0) str += ' disabled ';
            //     str += '/>';
            // } else {
                str += '<div class="placeholder placeholder-value-div">';
                str += '<input type="text" placeholder="输入数值" name="listData[' + i + '].setValue"  id="setValue' + list[i].detailNameCN + '"';
                if (_o.readWriteType == 0) str += ' disabled ';
                str += '/>';
            // }
            str += '</div></td></tr</table>';
        }
        $('#test-rule-page').html(str);

    } else {
        common.showMsgTips(resultData.msg);
    }

}

function CheckRuleStore() {
    var testerMode = {};
    testerMode['testTenantId'] = _testTenantId;
    testerMode['testUserId'] = _testUserId;
    testerMode['produceId'] = _produceId;
    testerMode['deviceTypeId'] = _deviceTypeId;
    testerMode['produceName'] = _produceName;
    $('#test-rule-page').find(':input').each(function () {
        if ($(this).attr('type') === 'radio') {
            if (this.checked) testerMode[$(this).attr('name').toString()] = $(this).val();
        } else {
            testerMode[$(this).attr('name').toString()] = $(this).val();
        }
    });
    console.log(testerMode);
    $.ajax({
        type: "post",
        url: common.CheckRuleStoreUrl,
        data: testerMode,
        success: function (result) {
            //这里是解析的json数据   直接返回data
            var resultData = result;
            var list = resultData.data;
            if (resultData.code == 0) {
                common.showMsgTips("保存成功");
            } else {
                common.showMsgTips(resultData.msg);
            }
            //数据格式
            //[{"code":0,"data":[{"attributeName":"温度","attributeValue":"0"},{"attributeName":"温度","attributeValue":"0"}],"msg":""}]
        }
    });
}


